package cron

import (
	"context"

	"code.bydev.io/frameworks/byone/core/logc"
)

func (d *Domain) SelfieCronHandler(ctx context.Context) error {
	logc.Infow(ctx, "SelfieCronHandler begin")

	initRecords, err := d.adminRepo.GetInitSelfieRecords(ctx, 100)
	if err != nil {
		logc.Errorw(ctx, "s.adminRepo.GetInitSelfieRecords error", logc.Field("err", err))
		return err
	}
	if len(initRecords) == 0 {
		logc.Infow(ctx, "no init records")
		return nil
	}
	logc.Infow(ctx, "s.adminRepo.GetInitSelfieRecords info", logc.Field("initRecords", initRecords))
	for _, record := range initRecords {
		isDone, err := d.adminRepo.IsRecordDone(ctx, record.Id)
		if err != nil {
			logc.Errorw(ctx, "s.adminRepo.IsRecordDone error", logc.Field("err", err))
			continue
		}
		if isDone {
			logc.Infow(ctx, "s.adminRepo.IsRecordDone is done", logc.Field("record", record))
			continue
		}
		err = d.handleImage(ctx, record)
		if err != nil {
			logc.Errorw(ctx, "s.handleImage error", logc.Field("record", record), logc.Field("err", err))
			continue
		}
		logc.Infow(ctx, "s.handleImage success", logc.Field("record", record))
	}
	logc.Infow(ctx, "SelfieCronHandler end")
	return nil
}
